package com.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {  // 过滤器类型 前 运行中 后 错误
        return "pre";
    }

    @Override
    public int filterOrder() {   // 过滤器优先级 返回值越小 优先级越高
        return 10;   // 保证可扩展性
    }

    @Override
    public boolean shouldFilter() {  // 是否执行该过滤器  布尔类型
        return true;
    }

    @Override
    public Object run() throws ZuulException {   // 过滤的业务逻辑
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isBlank(token)) {
            currentContext.setSendZuulResponse(false);

            currentContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            currentContext.setResponseBody("request error");
        }

        return null;
    }
}
